import React, { useCallback, useContext, useEffect, useImperativeHandle, useState } from 'react';
import { positionAPI } from '../../type';
import cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { AutoComplete, Button, Card, Col, Empty, Input, Row, Spin, Tooltip, Tree } from 'antd';
import { DoubleRightOutlined, DoubleLeftOutlined, SearchOutlined, CloseOutlined } from '@ant-design/icons';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { PositionContext } from '../../hooks';
import { usePositionOperation } from '../../hooks/usePositionOperation';
import { loopArray, transltateFn } from '@/utils';
import _ from 'lodash';

import '../../styles.less';

export const OtherStepRoule = React.forwardRef<positionAPI.IStepRef, positionAPI.IOtherStepRouleProps>(
  (
    {
      otherStepType, //判断是角色步骤还是管辖步骤  secondStep 角色步骤   || threeStep 管辖步骤 || fourStep  科目步骤
      treeIcon, //树的前置图标
      secondRouleID, //第二步选中的id
      secondRouleRows, //第二步选择的 row
      thirdData, //第三步的数据
      thirdPowerID, //第三步选择的 id
      thirdPowerRows, //第三步选择的 row
      fourthSubjectID, //第四步选择的 id
      fourthSubjectRows, //第四步选择的 row
      detailInfoData, //获取的详情数据
    },
    ref,
  ) => {
    const prefixCard = 'update-othercard'; //组件内部样式

    // 获取选中的岗位id
    const { curRes } = useContext(PositionContext);
    const [autoOptionLeft, setAutoOptionLeft] = useState<any[]>([]); //保存左侧 AutoComplete 的下拉菜单值
    const [autoOptionRight, setAutoOptionRight] = useState<any[]>([]); //保存AutoComplete 的下拉菜单值

    const [seachValueLeft, setSeachValueLeft] = useState<string>(''); //保存左侧树搜索的值
    const [seachValueRight, setSeachValueRight] = useState<string>(''); //保存右侧树搜索的值

    const [expandedKeys, setExpandedKeys] = useState<string[]>([]); //展开指定的树节点
    const [autoExpandParent, setAutoExpandParent] = useState<boolean>(false); //是否自动展开父节点

    const [rightRouleList, setRightRouleList] = useState<any>([]); //选中左侧树结构数据
    const [leftCheckKeys, setLeftCheckKeys] = useState<any>([]); //左侧树选中的key

    const { rouleData, rouleLoading, choiceLength } = usePositionOperation(curRes, otherStepType, thirdData); //角色树 数据

    // ref 逻辑处理
    useImperativeHandle(ref, () => ({
      leftCheckKeys: leftCheckKeys,
      rightRouleList: rightRouleList,
    }));

    // 初始化
    useEffect(() => {
      if (otherStepType == 'secondStep') {
        //第二步选择数据,初始化
        // 判断第二步 是否选中左侧 ID 或者 编辑时获取详情选中 ID , 以自主选中为主
        let secondIDs = secondRouleID && secondRouleID?.length > 0 ? secondRouleID : [];

        // 判断第二步 是否选中左侧 ROW 或者 编辑时获取详情选中 ROW , 以自主选中为主
        let secondRows = secondRouleRows && secondRouleRows?.length > 0 ? secondRouleRows : handEditDefaule(secondIDs);
        setLeftCheckKeys(!rouleLoading ? secondIDs : []);
        setRightRouleList(!rouleLoading ? secondRows : []);
      } else if (otherStepType == 'thirdStep') {
        //第三步选择数据初始化
        // 判断第三步 是否选中左侧 ID 或者 编辑时获取详情选中 ID , 以自主选中为主
        let thirdIDs = thirdPowerID && thirdPowerID?.length > 0 ? thirdPowerID : [];
        // 判断第三步 是否选中左侧 ROW 或者 编辑时获取详情选中 ROW , 以自主选中为主
        let thirdRows = thirdPowerRows && thirdPowerRows?.length > 0 ? thirdPowerRows : handEditDefaule(thirdIDs);
        setLeftCheckKeys(!rouleLoading ? thirdIDs : []);
        setRightRouleList(!rouleLoading ? thirdRows : []);
      } else if (otherStepType == 'fourthStep') {
        //第四步选择数据初始化
        // 判断第四步 是否选中左侧 ID 或者 编辑时获取详情选中 ID , 以自主选中为主
        let fourthIDs = fourthSubjectID && fourthSubjectID?.length > 0 ? fourthSubjectID : [];

        // 判断第三步 是否选中左侧 ROW 或者 编辑时获取详情选中 ROW , 以自主选中为主
        let fourthRows = fourthSubjectRows && fourthSubjectRows?.length > 0 ? fourthSubjectRows : handEditDefaule(fourthIDs);
        setLeftCheckKeys(!rouleLoading ? fourthIDs : []);
        setRightRouleList(!rouleLoading ? fourthRows : []);
      }
    }, [otherStepType, rouleLoading, secondRouleID, thirdPowerRows, fourthSubjectID]);

    // 处理编辑初始化数据
    const handEditDefaule = (defaultIDS: any) => {
      let allLeft = loopArray(rouleData);
      let checkRow: any = [];

      if (defaultIDS?.length > 0) {
        allLeft?.forEach((item: any) => {
          if (defaultIDS?.includes(item?.id)) {
            checkRow?.push({ ...item, children: null });
          }
        });
      }
      return checkRow;
    };

    // 左右两侧搜索框点击搜索
    const onSearch = useCallback(
      (e: React.ChangeEvent<HTMLInputElement>, list: any, seachType: string) => {
        const searchValue = e.target.value;
        if (seachType == 'left') {
          setSeachValueLeft(searchValue);
        } else if (seachType == 'right') {
          setSeachValueRight(searchValue);
        }
        const tileArray: Record<string, any>[] = seachType == 'left' ? loopArray(list) : seachType == 'right' ? list : [];

        if (searchValue && searchValue.length > 0) {
          const newOption: any[] = tileArray
            ?.map((item) => {
              if ((item?.name ?? item?.text)?.includes(searchValue)) {
                // const name = item?.name ?? item?.text;
                // const nameLength = name?.length;
                // const select = name?.search(searchValue);
                // const searchLength = searchValue?.length;
                // const afterStr = name?.slice(0, select);
                // const selectStr = searchValue;
                // const beforeStr = name?.slice(
                //   select + searchLength,
                //   nameLength,
                // );

                return {
                  value: item?.name ?? item?.text,
                  key: item?.id + otherStepType + seachType,
                  // label: (
                  //   <div>
                  //     <span>{afterStr}</span>
                  //     <span style={{ color: '#f50' }}>{selectStr}</span>
                  //     <span>{beforeStr}</span>
                  //   </div>
                  // ),
                  itemrowobj: { ...item },
                };
              }
            })
            ?.filter((item) => typeof item !== 'undefined');

          if (seachType == 'left') {
            setAutoOptionLeft(newOption);
          } else if (seachType == 'right') {
            setAutoOptionRight(newOption);
          }
        } else {
          if (seachType == 'left') {
            setAutoOptionLeft([]);
          } else if (seachType == 'right') {
            setAutoOptionRight([]);
          }
        }
      },
      [autoOptionLeft, autoOptionRight],
    );

    // 渲染树数据  Tree
    const orgTreeData = (data: any[]): any[] => {
      let disabled: boolean = false;
      return data?.map((item) => {
        const name = item?.name ?? item?.text;
        const nameLength = name?.length;
        const select = name?.search(seachValueLeft);
        const searchLength = seachValueLeft?.length;
        const afterStr = name?.slice(0, select);
        const selectStr = seachValueLeft;
        const beforeStr = name?.slice(select + searchLength, nameLength);
        const titleTree =
          select > -1 && selectStr ? (
            <Tooltip title={name}>
              <span className={pageStyles['over-flow-hidden']}>
                {afterStr}
                <span style={{ color: '#f50' }}>{selectStr}</span>
                {beforeStr}
              </span>
            </Tooltip>
          ) : (
            <Tooltip title={name}>
              <span className={pageStyles['over-flow-hidden']}>{item?.name ?? item?.text ?? '--'}</span>
            </Tooltip>
          );

        // 判断树节点复选框是否可选
        if (otherStepType == 'thirdStep' && item?.category == 0) {
          disabled = true;
        } else if (otherStepType == 'fourthStep' && item?.textType == 0) {
          disabled = true;
        } else {
          disabled = false;
        }

        if (item?.children) {
          return {
            ...item,
            title: (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  // paddingRight: 20,
                }}
                id={item?.id + otherStepType + 'left'}
              >
                {treeIcon}
                {titleTree}
              </div>
            ),
            key: item?.id,
            children: orgTreeData(item?.children),
            disabled: disabled,
          };
        }
        return {
          ...item,
          title: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                // paddingRight: 20,
              }}
              id={item?.id + otherStepType + 'left'}
            >
              {treeIcon}
              {titleTree}
            </div>
          ),
          key: item?.id,
          disabled: disabled,
        };
      });
    };

    // 左侧树 点击搜索
    const onAutoSelect = useCallback(
      (value: string, option: any, dataList: any[], seachType: string) => {
        const optionId = option?.key;
        if (seachType == 'left') {
          setSeachValueLeft(value);
          // const targetNode = loopArray(dataList)?.find( (i) => i?.id + otherStepType + seachType === optionId);
          const targetNode = loopArray(dataList); //平铺的树
          let rowObj = option?.itemrowobj;

          let openTreeIds = transltateFn(targetNode, rowObj?.pID);

          setAutoExpandParent(true);
          // onTreeSelectChange(option?.key);
          setExpandedKeys(openTreeIds);
        } else if (seachType == 'right') {
          setSeachValueRight(value);
        }

        // 滚动定位
        setTimeout(() => {
          scrollToAnchor(optionId);
        }, 1000);
      },
      [expandedKeys, rouleData, rightRouleList],
    );

    // 滚动定位
    const scrollToAnchor = (id: string) => {
      let anchorElement = document.getElementById(id);
      if (id) {
        anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
      }
    };

    // 点击展开关闭
    const onTreeExpand = useCallback(
      (e: any) => {
        setExpandedKeys(e);
        setAutoExpandParent(false);
      },
      [expandedKeys],
    );

    // 点击选择
    const onTreeSelect = useCallback(
      (checkedKeys: any, treeNodes: any) => {
        setRightRouleList(treeNodes?.checkedNodes);
        setLeftCheckKeys(checkedKeys?.checked);
      },
      [rightRouleList, leftCheckKeys],
    );

    // 点击右侧删除选中的标签
    const delRightTag = useCallback(
      (tagObj: any) => {
        let checkNode: any = []; //右侧选中的数据
        let leftKeys = _.cloneDeep(leftCheckKeys); //左侧选中的key
        leftKeys?.forEach((item: any, index: number) => {
          if (tagObj?.id == item) {
            leftKeys.splice(index, 1);
          }
        });
        checkNode = rightRouleList?.filter((nodeItem: any) => {
          return nodeItem?.id != tagObj?.id;
        });
        setRightRouleList(checkNode); //保存删除后 选中的数据
        setLeftCheckKeys(leftKeys); //保存删除后, 左侧 选中的key
      },
      [leftCheckKeys, rightRouleList],
    );

    // 全选与反选 为 AllSel 全选 为 AllRev 反选
    const selectReverseAll = useCallback(
      (type: string) => {
        if (type == 'AllSel') {
          const tileArray: Record<string, any>[] = loopArray(rouleData);
          let checkID: any = []; //保存全选的id
          let checkRow: any = []; //保存全选的 数据
          tileArray?.forEach((item: any) => {
            if (otherStepType == 'thirdStep' && item?.category == 1) {
              //第三步可选择数据
              checkID?.push(item?.id);
              checkRow?.push(item);
            } else if (otherStepType == 'fourthStep' && item?.textType == 1) {
              //第四步可一键全选的数据
              checkID?.push(item?.id);
              checkRow?.push(item);
            } else if (otherStepType == 'secondStep') {
              //第二步可一键全选的数据
              checkID?.push(item?.id);
              checkRow?.push(item);
            }
          });
          setRightRouleList(checkRow);
          setLeftCheckKeys(checkID);
        } else if (type == 'AllRev') {
          setRightRouleList([]); //清空右侧选择的数据
          setLeftCheckKeys([]); //清空左侧选择的 key
          setAutoOptionRight([]); //让右侧数据搜索清空
          setSeachValueRight(''); // 清空右侧保存的输入框的内容
        }
      },
      [leftCheckKeys, rightRouleList, rouleData],
    );

    return (
      <div className={cls('edit-step-layout')}>
        <Card bordered={false} style={{ width: '100%' }} bodyStyle={{ paddingBottom: 0, paddingTop: 5 }}>
          <Row className={cls(prefixCard)}>
            <Col span={11}>
              <Card
                bordered
                title={
                  <>
                    <AutoComplete
                      style={{ width: '100%' }}
                      options={autoOptionLeft}
                      notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                      onSelect={(value: string, option: any) => {
                        onAutoSelect(value, option, rouleData, 'left');
                      }}
                    >
                      <Input
                        suffix={<SearchOutlined />}
                        onChange={(e) => {
                          onSearch(e, rouleData, 'left');
                        }}
                        placeholder="请按名称搜索"
                        allowClear={true}
                      />
                    </AutoComplete>
                  </>
                }
              >
                <Spin spinning={rouleLoading} style={{ width: '100%', marginTop: '20px', overflow: 'scroll' }}>
                  <ScrollBarLayout
                    style={{
                      height: document.body.clientHeight * 0.4,
                      padding: '10px 0px',
                    }}
                  >
                    {rouleData && rouleData?.length > 0 ? (
                      <Tree
                        treeData={orgTreeData(rouleData)}
                        blockNode={true}
                        checkable={true}
                        autoExpandParent={autoExpandParent}
                        onCheck={onTreeSelect}
                        checkedKeys={leftCheckKeys}
                        expandedKeys={expandedKeys}
                        onExpand={onTreeExpand}
                        checkStrictly={true}
                        defaultExpandedKeys={expandedKeys}
                      />
                    ) : (
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    )}
                  </ScrollBarLayout>
                </Spin>
              </Card>
            </Col>
            <Col span={2}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: document.body.clientHeight * 0.4,
                }}
              >
                <Button
                  type={choiceLength == rightRouleList?.length && choiceLength != 0 ? 'dashed' : 'primary'}
                  style={{ marginBottom: 10 }}
                  onClick={() => {
                    selectReverseAll('AllSel');
                  }}
                  disabled={choiceLength == 0 ? true : rouleData && rouleData?.length > 0 ? false : true}
                  // onMouseOut={(event: any) => {
                  //   event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                  // }}
                >
                  <DoubleRightOutlined />
                </Button>
                <Button
                  type={choiceLength == rightRouleList?.length ? 'primary' : 'dashed'}
                  onClick={() => {
                    selectReverseAll('AllRev');
                  }}
                  disabled={choiceLength == 0 ? true : rouleData && rouleData?.length > 0 ? false : true}
                  // onMouseOut={(event: any) => {
                  //   event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                  // }}
                >
                  <DoubleLeftOutlined />
                </Button>
              </div>
            </Col>
            <Col span={11}>
              <Card
                bordered
                title={
                  <Row style={{ display: 'flex', alignItems: 'center' }}>
                    <Col span={8}>
                      已选：{rightRouleList?.length} / {choiceLength}
                    </Col>
                    <Col span={16}>
                      <AutoComplete
                        style={{ width: '100%' }}
                        options={autoOptionRight}
                        notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                        onSelect={(value: string, option: any) => {
                          onAutoSelect(value, option, rightRouleList, 'right');
                        }}
                      >
                        <Input
                          suffix={<SearchOutlined />}
                          onChange={(e) => {
                            onSearch(e, rightRouleList, 'right');
                          }}
                          placeholder="请按名称搜索"
                          allowClear={true}
                        />
                      </AutoComplete>
                    </Col>
                  </Row>
                }
              >
                <ScrollBarLayout
                  style={{
                    height: document.body.clientHeight * 0.4,
                    padding: '10px 0px',
                  }}
                >
                  {rightRouleList && rightRouleList.length > 0 ? (
                    <>
                      {rightRouleList.map((item: any, index: any) => {
                        const name = item?.name ?? item?.text;
                        const nameLength = name?.length;
                        const select = name?.search(seachValueRight);
                        const searchLength = seachValueRight?.length;
                        const afterStr = name?.slice(0, select);
                        const selectStr = seachValueRight;
                        const beforeStr = name?.slice(select + searchLength, nameLength);
                        const titleTree =
                          select > -1 && selectStr ? (
                            <span>
                              {afterStr}
                              <span style={{ color: '#f50' }}>{selectStr}</span>
                              {beforeStr}
                            </span>
                          ) : (
                            item?.name ?? item?.text
                          );
                        return (
                          <div
                            style={{ paddingTop: index == 0 ? '0px' : '' }}
                            className={cls(prefixCard + '-rightFather')}
                            id={item?.id + otherStepType + 'right'}
                            key={item?.id + otherStepType + 'right'}
                          >
                            <div className={cls(prefixCard + '-rightChild')}>
                              <div className={cls(prefixCard + '-rightChildIcon')}>
                                <div style={{ margin: '0px 5px 0px 10px' }}>{treeIcon}</div>
                                <div style={{ padding: '5px 0px' }}>{titleTree ?? '--'}</div>
                              </div>
                              <span
                                style={{
                                  margin: '0px 10px',
                                  cursor: 'pointer',
                                }}
                                onClick={(e) => {
                                  e?.stopPropagation();
                                  delRightTag(item);
                                }}
                              >
                                <CloseOutlined />
                              </span>
                            </div>
                          </div>
                        );
                      })}
                    </>
                  ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  )}
                </ScrollBarLayout>
              </Card>
            </Col>
          </Row>
        </Card>
      </div>
    );
  },
);
